//
//  MineViewController.m
//  GoBigMarket
//
//  Created by legend on 16/8/15.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "MineViewController.h"
#import "BalanceViewController.h"
#import "CouponViewController.h"
#import "IntegralViewController.h"
#import "AboutViewController.h"
#import "AboutViewController.h"
#import "ServiceViewController.h"
#import "OrdersViewController.h"
#import "WelcomViewController.h"
#import "AddressViewController.h"

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UIScrollView *scrollView;//底图
@property (nonatomic,strong)UIView *headerView;//头部视图
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *muArr;//数组

@property (nonatomic,strong)UIButton *picBtn;//头像
@property (nonatomic,strong)UILabel *nameLabel;//姓名

@property (nonatomic,strong)UIView *balanceView;//余额
@property (nonatomic,strong)UILabel *balanceLabel;//

@property (nonatomic,strong)UIView *couponView;//优惠券
@property (nonatomic,strong)UILabel *couponLabel;//

@property (nonatomic,strong)UIView *integralView;//积分
@property (nonatomic,strong)UILabel *integralLabel;//

@property (nonatomic,strong)BalanceViewController *balanceViewController;//我的余额页面
@property (nonatomic,strong)CouponViewController *couponViewController;//我的优惠券页面
@property (nonatomic,strong)IntegralViewController *integralViewController;//我的积分
@property (nonatomic,strong)AboutViewController *aboutViewController;//关于我们
@property (nonatomic,strong)ServiceViewController *serviceViewController;//服务条款页面
@property (nonatomic,strong)OrdersViewController *ordersViewController;//我的订单
@property (nonatomic,strong)WelcomViewController *login;
@property (nonatomic,strong)AddressViewController *addressVC;


@property (nonatomic,strong)NSMutableArray *picArr;

@property (nonatomic,strong)NSMutableDictionary *dicData;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _muArr = [NSMutableArray arrayWithObjects:@"我的订单",@"收货地址",@"服务条款",@"关于我们",@"联系我们",@"退出登录", nil];
    // Do any additional setup after loading the view.
    _picArr = [NSMutableArray arrayWithObjects:@"我的订单",@"Shape",@"矩形3",@"aboutUs",@"usPhone",@"Turn-off", nil];
    self.navigationItem.title = @"个人中心";
    self.view.backgroundColor = [UIColor whiteColor];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /**判断是否登录
     */
    NSUserDefaults * userLogon = [NSUserDefaults standardUserDefaults];
    NSString * isSignin_String = [userLogon objectForKey:LOGIN_STATUS];
    NSLog(@"等没等。。。%@",isSignin_String);
    if ([isSignin_String isEqualToString:@"未登录"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录,请先登录后再执行操作!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            WelcomViewController *welcomeVC = [[WelcomViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:welcomeVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alert dismissViewControllerAnimated:YES completion:nil];
            //获取Main.storyboard中的首页
            UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UITabBarController *tabBar = [mainStory instantiateViewControllerWithIdentifier:@"tabBarId"];
            self.view.window.rootViewController = tabBar;
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if([isSignin_String isEqualToString:@"已登录"]){
        [self netWorking];
        self.tabBarController.tabBar.hidden = NO;
        
        if (!self.dicData) {
            self.dicData = [NSMutableDictionary dictionary];
        }
    }
}
#pragma mark - SVProgressHUD
- (void)SVProgressHUDAction{
    //渐变而且禁止用户操作
    //    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
}

- (void)netWorking{
    [self SVProgressHUDAction];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    
    [CQNetWorkTools GETWithURL:GetMine par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID} success:^(id responseObject) {
        DLog(@"%@",responseObject);
        if ([[responseObject valueForKey:@"Err"]integerValue] != 0) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [SVProgressHUD dismissWithDelay:1.0f];
        }else{
            
            self.dicData = [NSMutableDictionary dictionaryWithDictionary:responseObject];
            
            [self.view addSubview:self.scrollView];
            
            NSString *balace = [NSString stringWithFormat:@"%@元",[responseObject valueForKey:@"Balance"]];
            NSString *coupon = [NSString stringWithFormat:@"%d张",[[responseObject valueForKey:@"UserCoupon"]intValue]];
            NSString *integra = [NSString stringWithFormat:@"%d分",[[responseObject valueForKey:@"Intergral"]intValue]];
            
            _balanceLabel.attributedText = [self strColorAndSizeWithStr:balace];
            _couponLabel.attributedText = [self strColorAndSizeWithStr:coupon];
            _integralLabel.attributedText = [self strColorAndSizeWithStr:integra];
            
            _nameLabel.text = [responseObject valueForKey:@"UserName"];
            
        }
        [SVProgressHUD dismissWithDelay:1.0f];
    } filed:^(NSError *error) {
        [SVProgressHUD dismissWithDelay:1.0f];
    }];
}

#pragma mark - scrollView;//底图
-(UIScrollView *)scrollView{
    
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, self.view.height - 49)];
    }
    _scrollView.pagingEnabled = YES;
    _scrollView.backgroundColor = XNColor(251, 251, 251, 1);
    _scrollView.contentSize = CGSizeMake(XNWindowWidth, 465);
//    _scrollView.bounces = NO;//关闭回弹
    _scrollView.showsVerticalScrollIndicator = NO;//垂直滚动指示器不显示
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    [_scrollView addSubview:self.headerView];
    [_scrollView addSubview:self.tableView];
    _scrollView.contentSize = CGSizeMake(XNWindowWidth, self.headerView.height + self.tableView.height);
    return _scrollView;
}

#pragma mark - headerView;//头部视图
-(UIView *)headerView{
    
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, 201)];
    }

//    _headerView.backgroundColor = [UIColor colorWithRed:0.46 green:0.75 blue:0.24 alpha:1.00];
    _headerView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:self.picBtn];//头像
    [_headerView addSubview:self.nameLabel];//昵称
    [_headerView addSubview:self.balanceView];//余额
    [_headerView addSubview:self.couponView];//优惠券
    [_headerView addSubview:self.integralView];//积分
    
    UIView *grayView1 = [[UIView alloc]initWithFrame:CGRectMake(self.balanceView.right, _balanceView.y, 1, _balanceView.height)];
    UIView *grayView2 = [[UIView alloc]initWithFrame:CGRectMake(self.couponView.right, _balanceView.y, 1, _balanceView.height)];
    UIView *grayView3 = [[UIView alloc]initWithFrame:CGRectMake(0, 120, XNWindowWidth, 1)];
    grayView3.backgroundColor = grayView1.backgroundColor = grayView2.backgroundColor = GDJBackColorGray;
    
    [_headerView addSubview:grayView1];
    [_headerView addSubview:grayView2];
    [_headerView addSubview:grayView3];
//    [self netWorking];
    return _headerView;
}

#pragma mark - picBtn;//头像
-(UIButton *)picBtn{
    
    if (!_picBtn) {
        _picBtn =[[UIButton alloc]initWithFrame:CGRectMake(20, 20, 80, 80)];
        [_picBtn setImage:[UIImage imageNamed:@"myselfPNG"] forState:0];
    }
    [_picBtn addTarget:self action:@selector(picBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _picBtn.backgroundColor = GDJColor(240, 240, 240);
    _picBtn.layer.masksToBounds = YES;
    _picBtn.layer.borderColor = [GDJColor(49, 164, 0) CGColor];
    _picBtn.layer.borderWidth = 2.4f;
    _picBtn.layer.cornerRadius = 40;
    return _picBtn;
}
//更换图片
- (void)picBtnAction:(UIButton *)picBtn{

//    WelcomViewController *login  = [[WelcomViewController alloc]init];
//    [self.navigationController pushViewController:login animated:YES];
}

#pragma mark - nameLabel;//姓名
-(UILabel *)nameLabel{
    
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(_picBtn.right + 10, 20, 130, 50)];
    }
    [_nameLabel setCenterY:_picBtn.centerY];
    _nameLabel.textAlignment = NSTextAlignmentLeft;
//    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.textColor = GDJGreenColor;
    return _nameLabel;
}

#pragma mark - BalanceView;//余额 balanceLabel
-(UIView *)balanceView{
    if (!_balanceView) {
        _balanceView = [[UIView alloc]initWithFrame:CGRectMake(0, 121, XNWindowWidth / 3, 80)];
    }
    _balanceView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 45, _balanceView.width, 30)];
    label.text = @"余额";
    label.textColor = GDJColor(102, 102, 102);
    label.textAlignment = NSTextAlignmentCenter;
    UIButton *btn = [[UIButton alloc]initWithFrame:_balanceView.bounds];
    [btn addTarget:self action:@selector(balanceBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_balanceView addSubview:label];
    [_balanceView addSubview:[self balanceLabel]];
    [_balanceView addSubview:btn];
    return _balanceView;
}
-(UILabel *)balanceLabel{
    
    if (!_balanceLabel) {
        _balanceLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, _balanceView.width, 40)];
    }
    _balanceLabel.textAlignment = NSTextAlignmentCenter;
    _balanceLabel.textColor = GDJColor(225, 139, 36);
    _balanceLabel.font = [UIFont systemFontOfSize:13];
    return _balanceLabel;
}

-(void)balanceBtnAction:(UIButton *)btn{
    if (!_balanceViewController) {
        _balanceViewController = [[BalanceViewController alloc]init];
    }
    
    self.balanceViewController.money =[self.dicData valueForKey:@"Balance"];
    [self.navigationController pushViewController:_balanceViewController animated:YES];
}

#pragma mark - couponView;//优惠券 couponLabel
-(UIView *)couponView{
    if (!_couponView) {
        _couponView = [[UIView alloc]initWithFrame:CGRectMake(_balanceView.right, 121, XNWindowWidth / 3, 80)];
    }
    _couponView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 45, _couponView.width, 30)];
    label.text = @"优惠券";
    label.textColor = GDJColor(102, 102, 102);
    label.textAlignment = NSTextAlignmentCenter;
    UIButton *btn = [[UIButton alloc]initWithFrame:_couponView.bounds];
    [btn addTarget:self action:@selector(couponBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_couponView addSubview:label];
    [_couponView addSubview:self.couponLabel];
    [_couponView addSubview:btn];
    return _couponView;
}
-(UILabel *)couponLabel{
    if (!_couponLabel) {
        _couponLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, _couponView.width, 40)];
    }
    _couponLabel.textAlignment = NSTextAlignmentCenter;
    _couponLabel.textColor = GDJColor(225, 139, 36);
    _couponLabel.font = [UIFont systemFontOfSize:13];
    return _couponLabel;
}
-(void)couponBtnAction:(UIButton *)btn{
     
//    if (!_couponViewController) {
//        _couponViewController = [[CouponViewController alloc]init];
//    }
//    [self.navigationController pushViewController:_couponViewController animated:YES];
}
#pragma mark - integralView;//积分 integralLabel
-(UIView *)integralView{
    if (!_integralView) {
        _integralView = [[UIView alloc]initWithFrame:CGRectMake(_couponView.right, 121, XNWindowWidth / 3, 80)];
    }
    _integralView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 45, _integralView.width, 30)];
    label.text = @"积分";
     label.textColor = GDJColor(102, 102, 102);
    label.textAlignment = NSTextAlignmentCenter;
    UIButton *btn = [[UIButton alloc]initWithFrame:_integralView.bounds];
    [btn addTarget:self action:@selector(integralbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_integralView addSubview:label];
    [_integralView addSubview:[self integralLabel]];
    [_integralView addSubview:btn];
    return _integralView;
}
-(UILabel *)integralLabel{
    if (!_integralLabel) {
        _integralLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, _integralView.width, 40)];
    }
    _integralLabel.textAlignment = NSTextAlignmentCenter;
    _integralLabel.textColor = GDJColor(225, 139, 36);
    _integralLabel.font = [UIFont systemFontOfSize:13];
//    _integralLabel.text = @"00分";
    return _integralLabel;
}
#pragma mark - 积分点击事件
- (void)integralbtnAction:(UIButton *)btn{
//    if (!_integralViewController) {
//        _integralViewController = [[IntegralViewController alloc]init];
//    }
//    _integralViewController.num = 10;
//    [self.navigationController pushViewController:_integralViewController animated:YES];
}
#pragma mark - tableView
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, _headerView.bottom + 2, XNWindowWidth, 300)style:UITableViewStylePlain];
    }
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.bounces = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorInset = UIEdgeInsetsMake(0,0, 0, 0);
    _tableView.separatorColor = GDJColor(251, 251, 251);
    
    return _tableView;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _muArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mineCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"mineCell"];
    }
    NSString *picName = _picArr[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:picName];
        
    cell.textLabel.text = _muArr[indexPath.row];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//辅助图标 向右的箭头
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    DLog(@"点击了%@",cell.textLabel.text);
    //退出登录
    
    if (indexPath.row == 5) {
        
        __weak typeof(self) weakSelf = self;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"要退出登录吗?" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *centerAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf exitApp];
            NSUserDefaults *account = [NSUserDefaults standardUserDefaults];
            [account setObject:@"未登录" forKey:LOGIN_STATUS];
            [account synchronize];

        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:centerAction];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:^{
            
        }];
    }
    
    switch (indexPath.row) {
        case 0://我的订单
            
            if (!_ordersViewController) {
                _ordersViewController = [[OrdersViewController alloc]init];
            }
            [self.navigationController pushViewController:_ordersViewController animated:YES];
            break;
        case 1://收货地址
            if (!_addressVC) {
                _addressVC = [[AddressViewController alloc]init];
            }
            [self.navigationController pushViewController:_addressVC animated:YES];
            break;
        case 2://服务条款
            if (!_serviceViewController) {
                _serviceViewController = [[ServiceViewController alloc]init];
            }
            [self.navigationController pushViewController:_serviceViewController animated:YES];
            break;
        case 3://关于我们
            if (!_aboutViewController) {
                _aboutViewController = [[AboutViewController alloc]init];
            }
            [self.navigationController pushViewController:_aboutViewController animated:YES];
            break;
        case 4://联系我们
            [self callPhone];
            break;
        default:
            break;
    }
}
//字体变色
- (NSAttributedString *)strColorAndSizeWithStr:(NSString *)str{
    //售价
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSForegroundColorAttributeName value:GDJColor(225, 139, 36) range:NSMakeRange(0, str.length - 1)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:23] range:NSMakeRange(0, str.length - 1)];
    
    return attributedString;
}
#pragma mark - 联系我们打电话
- (void)callPhone{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"感谢" message:@"欢迎致电我们。收到您的来电是我们的荣幸!" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *phoneAction1 = [UIAlertAction actionWithTitle:@"座机1：0539-295 2317" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DLog(@"电话：0539-2952317");
        NSString *phone = [NSString stringWithFormat:@"tel://%@",@"05392952317"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
    }];
    UIAlertAction *phoneAction2 = [UIAlertAction actionWithTitle:@"座机2：0539-295 2318" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DLog(@"电话：0539-2952318");
        NSString *phone = [NSString stringWithFormat:@"tel://%@",@"05392952318"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"下次再打吧" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:phoneAction1];
    [alertController addAction:phoneAction2];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 退出登录
- (void)exitApp{
    if (!_login) {
        _login  = [[WelcomViewController alloc]init];
    }
    
    [CQNetWorkTools POSTWithURL:PostExitApp par:@{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN} success:^(id responseObject) {
        if ([[responseObject valueForKey:@"Err"]intValue] == 0) {
            
            [self.navigationController pushViewController:_login animated:YES];
            //移除本地数据
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"phoneNum"];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"Token"];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"XuanZeAddress"];
            
            //删除钥匙串中的UUID
            [UUID delUUID];
        }else{
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
    } filed:^(NSError *error) {
        DLog(@"%@",error);
    }];

}
@end
